package demo19_Lock;

import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author kunkun
 * @className Test04_DiySpinLock
 * @Description 自定义自旋锁
 * @date 2025/3/8 22:50
 */
public class Test04_DiySpinLock {
    public AtomicReference<Thread> atomicReference = new AtomicReference<>();   //cas操作

    public void lock(){

        //自旋锁
        while(!atomicReference.compareAndSet(null,Thread.currentThread())){ //如果当前线程不是空，就一直等待，第一个过去的人将null改为Thread

        }
        System.out.println("当前获得锁的线程："+Thread.currentThread().getName());
    }

    public void unlock(){
        System.out.println("当前解开锁的线程："+Thread.currentThread().getName()+"----unlock");
        //自旋锁
        atomicReference.compareAndSet(Thread.currentThread(),null);
    }



}
